package com.soft.idc.module.device;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.jetty.util.log.Log;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.CaptchaRender;
import com.soft.idc.common.control.AuthInterceptor;
import com.soft.idc.common.model.IdcOrg;
import com.soft.idc.common.model.IdcRole;
import com.soft.idc.common.model.IdcUser;
import com.soft.idc.common.util.JQList;
import com.soft.idc.common.util.JQPage;

@Before(AuthInterceptor.class)
public class DeviceController extends Controller {

	public void index() {
		IdcOrg org = (IdcOrg) this.getSessionAttr("SYS_USER_ORG");
		// 查出组织
		String sql = "select org_id,name from idc_org o where o.parent_id != -1 and org_type = 0 ";

		List<Record> orgList = null;
		if (org.getOrgId() != 1) {
			sql += " and org_id = ?";
			orgList = Db.find(sql, org.getOrgId());
		} else {
			orgList = Db.find(sql);
		}

		this.setAttr("ORG_LIST", orgList);

		this.renderJsp("/device/main.jsp");
	}

	public void loadDevicesInfo() {
		IdcUser u = (IdcUser) this.getSessionAttr("SYS_USER");
		String countSql = "select * from idc_device_count where org_id = ? order by createtime desc limit 1";
		String warnSql = "select * from idc_device_org_warn where org_id = ? order by createtime desc limit 1";
		Record count = Db.findFirst(countSql, u.getOrgId());
		Record warn = Db.findFirst(warnSql, u.getOrgId());
		this.setAttr("count", count);
		this.setAttr("warn", warn);
		this.renderJson();
	}

	public void loadWifiFlow() {
		/*
		 * String sql =
		 * "select upflow,downflow,create_time from idc_plane_wififlow where plane_id = ? order by create_time desc limit 0,?"
		 * ; int length = this.getParaToInt("length", 5); String planeId =
		 * this.getPara("planeId"); List<Record> flow = Db.find(sql, planeId,
		 * length);
		 */
		String sql = " select date_format(create_time,'%Y-%m-%d %H:%i:00') as create_time,sum(value) as value from idc_kpi_record "
				+ "where  obj_type = 0 and obj_id in (select device_id from idc_device where type_id =105 and plane_id = ?)"
				+ "and kpi_id = 100027 and create_time >= str_to_date(?,'%Y-%m-%d %H:%i:%s') group by create_time order by create_time asc";
		int length = this.getParaToInt("length", 5);
		String planeId = this.getPara("planeId");
		String createTime = this.getPara("createTime");
		List<Record> flow = Db.find(sql, planeId, createTime);

		this.renderJson(flow);
	}

	public void loadWifiWarn() {
		String sql = "select * from idc_plane_wifiwarn where plane_id = ? and create_time >= str_to_date(?,'%Y-%m-%d %H:%i:%s') order by create_time asc";
		int length = this.getParaToInt("length", 5);
		String planeId = this.getPara("planeId");
		String createTime = this.getPara("createTime");
		List<Record> flow = Db.find(sql, planeId, createTime);

		this.renderJson(flow);
	}

	public void loadDeviceKpi() {
		String sql = "select kpi_id,value from idc_kpi_record_ing"
				+ " where  obj_type = 0 and obj_id in (select device_id from idc_device where type_id in (104,106) and plane_id = ?) "
				+ " and kpi_id in (100019,100154,100127,100155)";
		String planeId = this.getPara("planeId");
		List<Record> list = Db.find(sql, planeId);
		Map<String, String> map = new HashMap<String, String>();
		for (Record vo : list) {
			String kpiId = vo.getInt("kpi_id") + "";
			if ("100019".equals(kpiId)) {
				map.put("servercpu", vo.getStr("value"));
			} else if ("100154".equals(kpiId)) {
				map.put("servermem", vo.getStr("value"));
			} else if ("100127".equals(kpiId)) {
				map.put("cmtcpu", vo.getStr("value"));
			} else if ("100155".equals(kpiId)) {
				map.put("cmtmem", vo.getStr("value"));
			}
		}

		this.renderJson(map);
	}

	public void loadTopo() {
		int planeId = this.getParaToInt("planeId");
		String sql0 = "select device_id,name from idc_device where plane_id = ?;";
		List<Record> list0 = Db.find(sql0, planeId);

		String sql = "select * from idc_device_topo";
		List<Record> deviceList = Db.find(sql);
		for (Record vo : deviceList) {
			String type_code = vo.getStr("type_code");
			if (type_code != null && !"".equals(type_code)) {
				for (Record vo0 : list0) {
					String name = vo0.getStr("name").toUpperCase();
					if (name.indexOf(type_code) != -1) {
						vo.set("device_id", vo0.getInt("device_id"));
						break;
					}
				}
			}
		}

		String sqlLink = "select (select key_type from idc_device_topo where id = l.aNode_id) as aNode,(select key_type from idc_device_topo where id = l.zNode_id) as zNode from idc_link_topo l where type = ?";
		List<Record> linkList = Db.find(sqlLink, "device_topo");

		this.setAttr("dpd_device_topo", deviceList);
		this.setAttr("dpd_device_link", linkList);
		this.renderJson();
	}

	public void loadDeviceStatus() {
		String deviceIds = this.getPara("deviceIds");

		String[] str = deviceIds.split(",");
		String tmp = "";
		Object[] objs = new Object[str.length];
		for (int i = 0; i < str.length; i++) {
			tmp += "?,";
			objs[i] = str[i];
		}
		tmp = tmp.substring(0, tmp.length() - 1);
		String sqlStatus = "select d.device_id,d.type_id,k.value from idc_device d "
				+ " left join idc_kpi_record_ing k on k.obj_id = d.device_id and k.kpi_id in (100022,100025,100030) "
				+ " where d.device_id in (" + tmp + ")";
		List<Record> list = Db.find(sqlStatus, objs);
		this.renderJson(list);

	}

	public void loadTopoWarn() {
		String deviceIds = this.getPara("deviceIds");
		String[] str = deviceIds.split(",");
		String tmp = "";
		Object[] objs = new Object[str.length];
		for (int i = 0; i < str.length; i++) {
			tmp += "?,";
			objs[i] = str[i];
		}
		tmp = tmp.substring(0, tmp.length() - 1);
		String sql = "select obj_id,type_id,count(1) as count from idc_warn_record where obj_id in (" + tmp
				+ ") and obj_type = 0 and is_clear=0 group by obj_id";
		List<Record> deviceList = Db.find(sql, objs);

		this.renderJson(deviceList);
	}

	public void loadPlanes() {
		int start = this.getParaToInt("start", 1);
		int length = this.getParaToInt("length", 10);
		int pageNum = start / length + 1;
		String orgId = this.getPara("org_id");
		IdcUser user = (IdcUser) this.getSessionAttr("SYS_USER");

		// light_id,flight_code,plane_code,people,wifi_people
		String sql = "select a.plane_id,a.code as plane_code,f.flight_code,f.flight_id,f.from_airport,f.to_airport,f.wifi_people,f.fly_time,f.plan_land_time,max(f.fly_time)";
		String sqlFrom = "from  idc_airplane a left join idc_flight_info f on f.plane_id = a.plane_id ";

		if (user.getOrgId() != 1) {
			sqlFrom += " and f.org_id = ?";
		} else {
			sqlFrom += " and f.org_id != ?";
		}
		sqlFrom += " group by a.plane_id order by f.fly_time desc";
		Page<Record> page = Db.paginate(pageNum, length, sql, sqlFrom, orgId);

		JQPage jPage = new JQPage(page);
		this.renderJson(jPage);
	}

	public void showDetail() {
		String planeId = this.getPara("plane_id");
		String planeCode = this.getPara("plane_code");
		IdcOrg org = (IdcOrg) this.getSessionAttr("SYS_USER_ORG");
		this.setAttr("org_name", org.getName());
		this.setAttr("plane_id", planeId);
		this.setAttr("plane_code", planeCode);
		this.renderJsp("/device/detail.jsp");
	}

	/**
	 * 详情页面cap列表
	 */
	public void loadCap() {
		int planeId = this.getParaToInt("planeId");
		String capKpiId = PropKit.get("dp_cap_kpi");
		String sql = "select obj_id,kpi_id,(select name from idc_device d where d.device_id = k.obj_id) obj_name,value,create_time from idc_kpi_record_ing k "
				+ " where  obj_type = 0 and obj_id in (select device_id from idc_device where type_id =105 and plane_id = ?) "
				+ " and kpi_id in (" + capKpiId + ") ";
		List<Record> list = Db.find(sql, planeId);
		Map<String, Map> map = new HashMap<String, Map>();
		for (Record vo : list) {
			String name = vo.getStr("obj_name");
			String deviceId = vo.getInt("obj_id") + "";
			Map cap = null;
			if (map.containsKey(name)) {
				cap = map.get(name);
			} else {
				cap = new HashMap();
				map.put(name, cap);
				cap.put("cap_name", name);
				cap.put("device_id", deviceId);
			}
			cap.put(PropKit.get(vo.getInt("kpi_id") + ""), vo.getStr("value"));
		}

		List result = new ArrayList();
		Set s = map.keySet();
		Iterator it = s.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			result.add(map.get(key));
		}

		Comparator<Map> comparator = new Comparator<Map>() {
			public int compare(Map m1, Map m2) {
				int deviceId1 = Integer.parseInt((String) m1.get("device_id"));
				int deviceId2 = Integer.parseInt((String) m2.get("device_id"));
				// 先排年龄
				return deviceId1 - deviceId2;
			}
		};
		Collections.sort(result, comparator);
		this.renderJson(new JQList(result));
	}

	public void loadServerInfo() {
		int planeId = this.getParaToInt("planeId");
		int typeId = this.getParaToInt("typeId");
		String serverKpiId = null;
		if (typeId == 104) {
			serverKpiId = PropKit.get("dp_server_kpi");
		} else if (typeId == 106) {
			serverKpiId = PropKit.get("dp_cmt_kpi");
		}
		String sql = "select obj_id,kpi_id,(select code from idc_kpi_define kd where kd.kpi_id =k.kpi_id ) kpi_code,(select name from idc_device d where d.device_id = k.obj_id) obj_name,value,create_time from idc_kpi_record_ing k  "
				+ " where  obj_type = 0 and obj_id in (select device_id from idc_device where type_id =? and plane_id = ?) "
				+ " and kpi_id in (" + serverKpiId + ") ";
		List<Record> list = Db.find(sql, typeId, planeId);
		Map<String, String> map = new HashMap<String, String>();
		for (Record vo : list) {
			map.put(vo.getStr("kpi_code"), vo.getStr("value"));
		}
		this.renderJson(map);
	}

	public void loadAppInfo() {
		int planeId = this.getParaToInt("planeId");
		int typeId = this.getParaToInt("typeId");
		String serverKpiId = null;
		if (typeId == 104) {
			serverKpiId = PropKit.get("dp_server_app_kpi");
		} else if (typeId == 106) {
			serverKpiId = PropKit.get("dp_cmt_app_kpi");
		}

		String sql = "select obj_id,kpi_id,(select code from idc_kpi_define kd where kd.kpi_id =k.kpi_id ) kpi_code,(select name from idc_device d where d.device_id = k.obj_id) obj_name,value,create_time from idc_kpi_record_ing k  "
				+ " where  obj_type = 0 and obj_id in (select device_id from idc_device where type_id =? and plane_id = ?) "
				+ " and kpi_id in (" + serverKpiId + ") ";
		List<Record> list = Db.find(sql, typeId, planeId);
		Map<String, Map> map = new HashMap<String, Map>();
		for (Record vo : list) {
			String name = vo.getStr("kpi_code");
			String[] str = name.split("\\.");
			Map app = null;
			if (map.containsKey(str[2])) {
				app = map.get(str[2]);
			} else {
				app = new HashMap();
				map.put(str[2], app);
				app.put("app_name", str[2]);
			}
			if (name.indexOf(".status") != -1) {
				app.put("app_status", vo.getStr("value"));
			} else if (name.indexOf(".runtime") != -1) {
				app.put("app_runtime", vo.getStr("value"));
			}

		}

		List result = new ArrayList();
		Set s = map.keySet();
		Iterator it = s.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			result.add(map.get(key));
		}

		this.renderJson(new JQList(result));
	}

	public void loadDisk() {
		int planeId = this.getParaToInt("planeId");
		int typeId = this.getParaToInt("typeId");
		String diskKpi = null;
		if (typeId == 104) {
			diskKpi = PropKit.get("dp_server_disk_kpi");
		} else if (typeId == 106) {
			diskKpi = PropKit.get("dp_cmt_disk_kpi");
		}

		String sql = "select obj_id,kpi_id,(select code from idc_kpi_define kd where kd.kpi_id =k.kpi_id ) kpi_code,(select name from idc_device d where d.device_id = k.obj_id) obj_name,value,create_time from idc_kpi_record_ing k  "
				+ " where  obj_type = 0 and obj_id in (select device_id from idc_device where type_id =? and plane_id = ?) "
				+ " and kpi_id in (" + diskKpi + ") ";
		Record vo = Db.findFirst(sql, typeId, planeId);
		List list = new ArrayList();
		if (vo != null) {
			String value = vo.getStr("value");
			String[] str = value.split("\\|");
			for (String s : str) {
				String[] params = s.split("\\,");
				Map map = new HashMap();
				map.put("path", params[0]);
				map.put("rate", params[1]);
				map.put("used", params[2]);
				map.put("free", params[3]);
				list.add(map);
			}
		}
		this.renderJson(new JQList(list));
	}

	public void loadDevices() {
		int start = this.getParaToInt("start");
		int length = this.getParaToInt("length");
		int pageNum = start / length + 1;
		String deviceType = this.getPara("deviceType");
		IdcUser user = (IdcUser) this.getSessionAttr("SYS_USER");

		String sql = "select d.device_id,d.code,d.is_use,d.name as device_name,a.code as plane_code ";
		String sqlFrom = "from idc_device d " + "join idc_airplane a on d.plane_id = a.plane_id where 1=1";

		if (deviceType == null || "".equals(deviceType)) {
			//
		} else if ("KU".equals(deviceType)) {
			String ids = PropKit.get("KU_TYPE_ID");
			sqlFrom += " and d.type_id in (" + ids + ")";
		} else if ("CMT".equals(deviceType)) {
			String id = PropKit.get("CMT_TYPE_ID");
			sqlFrom += " and d.type_id = " + id;
		} else if ("CAP".equals(deviceType)) {
			String id = PropKit.get("CAP_TYPE_ID");
			sqlFrom += " and d.type_id = " + id;
		} else if ("3G".equals(deviceType)) {
			String id = PropKit.get("3G_TYPE_ID");
			sqlFrom += " and d.type_id = " + id;
		} else if ("SERVER".equals(deviceType)) {
			String id = PropKit.get("SERVER_TYPE_ID");
			sqlFrom += " and d.type_id = " + id;
		}

		List<Record> list = null;
		if (user.getOrgId() != 1) {
			sqlFrom += " and d.org_id = ?";
		} else {
			sqlFrom += " and d.org_id != ?";
		}
		Page<Record> page = Db.paginate(pageNum, length, sql, sqlFrom, user.getOrgId());

		JQPage jPage = new JQPage(page);
		this.renderJson(jPage);
	}

	public void loadAreaLable() {
		// String level = this.getPara("level");
		String sql = "select city,lng,lat,level from idc_airport_gps g";
		List<Record> result = Db.find(sql);
		this.renderJson(result);
	}

}
